//
//  HMNetworkTool.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/11.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import AFNetworking

// MARK: - 请求方法枚举
enum HMNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class HMNetworkTool: NSObject {
    // 单例, 调用默认构造方法
    static let shared: HMNetworkTool = HMNetworkTool()
    
    private var afnManager: AFHTTPSessionManager
    
    // 将唯一的构造方法私有化,外部无法通过构造函数来初始化对象了
    private override init() {
        let baseURL = URL(string: "https://api.weibo.com/")
        afnManager = AFHTTPSessionManager(baseURL: baseURL)
        
        // 设置响应的序列化器,支持text/plain
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }
    
    /// 自己来封装GET请求,外面都直接调用requestGET,如果AFN以后不好用,想换其他的框架或者AFN升级请求参数更换了,我们只需要修改requestGET里面的内容,外面不同修改
    private func requestGET(URLString: String, parameters: Any?, progress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) {
        
        // 调用AFN的get
        afnManager.get(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
    }
    
    private func requestPOST(URLString: String, parameters: Any?, progress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) {
        
        // 调用AFN的post
        afnManager.post(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
    }
    
    func request(method: HMNetworkMethod, URLString: String, parameters: Any?, progress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> Void {
        switch method {
        case .GET:
            // 调用AFN的get
            afnManager.get(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
            
        case .POST:
            // 调用AFN的post
            afnManager.post(URLString, parameters: parameters, progress: progress, success: success, failure: failure)
        }
    }
    
    func requestPost(URLString: String, parameters: Any?, constructingBodyWith: ((AFMultipartFormData) -> Void)?, progress: ((Progress) -> Void)?, success: ((URLSessionDataTask, Any?) -> Void)?, failure: ((URLSessionDataTask?, Error) -> Void)?) -> Void {
        afnManager.post(URLString, parameters: parameters, constructingBodyWith: constructingBodyWith, progress: progress, success: success, failure: failure)
    }
}
